﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using BartonExtension;

using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin;

using WeixinModel;
using Model;

namespace XiJiaXi
{
    public class AccessTokenHelper
    {
        public const string AppKey = "wxc5ab249aafdc8ae5";
        public const string AppSecret = "c1b666d0b89730743e5d245da857f7f5";

        public static string GetAuthUrl(string state,string redirectUrl)
        {
            return OAuthApi.GetAuthorizeUrl(AppKey, redirectUrl, state, OAuthScope.snsapi_userinfo);
        }
        public static AccessToken GetAccessTokenFromWeixinService(string code)
        {
            try
            {
                OAuthAccessTokenResult weixin_token = OAuthApi.GetAccessToken(AppKey, AppSecret, code);
                if (weixin_token.errcode != ReturnCode.请求成功)
                {
                    return null;
                }

                AccessToken acs_token = new AccessToken()
                {
                    access_token = weixin_token.access_token,
                    openid = weixin_token.openid,
                    createTime = DateTime.Now,
                    expiredTime = weixin_token.expires_in,
                    refresh_token = weixin_token.refresh_token
                };
                return acs_token;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}